﻿<template>
  <a-card :bordered="false">
    <a-modal
      title="选择"
      width="40%"
      :visible="show"
      :confirm-loading="modalLoading"
      @ok="saveAllocation"
      @cancel="
        () => {
          this.show = false
        }
      "
    >
      <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
        <!-- v-model="entity.DepartmentId" -->
        <a-form-model-item label="选择组织机构" prop="DepartmentId">
          <a-tree-select
            @change="Department($event)"
            allowClear
            :treeData="DepartmentIdTreeData"
            placeholder="请选择组织机构"
            treeDefaultExpandAll
            v-model="DepartmentId"
          ></a-tree-select>
        </a-form-model-item>

        <a-form-model-item label="选择用户" prop="SalesmanId">
          <a-select
            allowClear
            showSearch
            :filter-option="filterOption"
            v-model="entity.SalesmanId"
            @change="changeSelect"
          >
            <a-select-option v-for="item in User" :key="item.Id" :value="item.Id">
              {{ item.RealName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <div class="table-operator">
      <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>

      <a-button
        style="margin-left: 8px"
        type="primary"
        @click="dormancy(selectedRowKeys)"
        :disabled="!hasSelected()"
        :loading="loading"
        >一键休眠
      </a-button>
    </div>

    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item label="客户名称">
              <!-- <a-input
                @pressEnter="
                  () => {
                    this.pagination.current = 1
                    this.getDataList()
                  }
                "
                v-model="queryParam[0].Keyword"
                placeholder="客户名称"
              /> -->
              <searchTip
                v-model="queryParam[0].Keyword"
                style=""
                placeholder="客户名称"
                :list="searchTipResultList"
                @enterKeyDown="
                  () => {
                    this.pagination.current = 1
                    this.getDataList()
                  }
                "
                @change="toGetSearchTipList"
                @blur="keywordBlurFun"
                @select="selectSearchTipFun"
              />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item label="交易截止日期">
              <a-date-picker :allowClear="false" format="YYYY-MM-DD" style="width: 100%" v-model="DormancySetDate" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-button
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }
              "
              >查询</a-button
            >
            <a-button style="margin-left: 8px" @click="Repossess">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-table
      ref="table"
      :scroll="{ y: 530 }"
      :columns="columns"
      :rowKey="(row, index) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="true"
      size="small"
    >
      <template slot="cCusType" slot-scope="text, record">
        <a-tag v-if="record.cCusType === 0" color="blue">潜在</a-tag>
        <a-tag v-else-if="record.cCusType === 1" color="green">正式</a-tag>
        <a-tag v-else-if="record.cCusType === 2" color="red">休眠</a-tag>
        <a-tag v-else-if="record.cCusType === 3" color="orange">待转正</a-tag>
      </template>
      <!-- :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, getCheckboxProps: CheckboxProps }" -->
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <span slot="action" slot-scope="text, record">
        <template>
          <!-- <a v-if="hasPerm('Customer.assign')" @click="follow(record)">指派</a> -->
          <a @click="dormancy([record.Id])">休眠</a>

          <a-divider type="vertical" />
          <a v-if="hasPerm('Customer.detail')" @click="handleEdit(record)">详情</a>
        </template>
      </span>
    </a-table>

    <EditForm ref="details" :parentObj="this"></EditForm>
    <Details ref="Detail" :parentObj="this"></Details>
    <PllAOO ref="PllAOO" />
    <MyCustomer ref="MyCustomer" :IsFormal="IsFormal" :parentObj="this"></MyCustomer>

    <List ref="List" />
  </a-card>
</template>

<script>
// 客户分配
import MyCustomer from '../MyCustomer/EditForm.vue'
import EditForm from './EditForm.vue'
import Details from './Details.vue'
import PllAOO from './PllAOO.vue'

import List from '../Cust_CustomerLinkMan/List.vue'
import moment from 'moment'
import searchTip from '@/components/components/SearchTip.vue'

const columns = [
  { title: '客户编码', dataIndex: 'cCusCode', width: '150px' },
  { title: '客户名称', dataIndex: 'cCusName', align: 'left', width: '320px' },
  // { title: '开户银行', dataIndex: 'cCusBank', align: 'left', width: '220px', ellipsis: true },
  // { title: '地址', dataIndex: 'cCusAddress', ellipsis: true },
  { title: '客户分组', dataIndex: 'GroupName', width: '180px' },
  { title: '业务负责人', dataIndex: 'PrincipalName', width: '180px', align: 'center' },
  {
    title: '最后订单日期',
    dataIndex: 'LastDate',
    width: '180px',
    align: 'center',
    customRender: (value) => {
      if (value) {
        return value.substring(0, 10)
      } else {
        return '无订单'
      }
    },
  },

  // { title: '联系人', dataIndex: 'cCusPerson', width: '230px' },
  {
    title: '客户类型',
    dataIndex: 'cCusType',
    align: 'center',
    width: '100px',
    // customRender: (value) => {
    //   if (value == 0) return '潜在'
    //   if (value == 1) return '正式'
    //   if (value == 2) return '休眠'
    // },
    scopedSlots: { customRender: 'cCusType' },
  },
  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' }, width: '130px' },
]

export default {
  components: {
    EditForm,
    List,
    MyCustomer,
    Details,
    PllAOO,
    searchTip,
  },
  mounted() {
    this.getDataList()
    this.DormancySetDate = moment(new Date())
    this.$http.post('/Base_Manage/Base_Department/GetTreeDataList', {}).then((resJson) => {
      if (resJson.Success) {
        this.DepartmentIdTreeData = resJson.Data
      }
    })
  },
  data() {
    return {
      DormancySetDate: moment(new Date()),
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 },
      },

      rules: {
        Type: [{ required: true, message: '请选择业务类型', trigger: 'change' }],
        SalesmanId: [{ required: true, message: '请选择用户', trigger: 'change' }],
      },
      DepartmentId: '',
      DepartmentIdTreeData: [],
      show: false,
      IsFormal: true,
      data: [],
      list: [], // 省级
      User: [],

      listChildren: [], // 市
      county: [], // 县
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true,
      },
      filters: {},
      entity: {},
      sorter: { field: 'LastDate', order: 'asc' },

      queryParam: [
        {
          Condition: 'cCusName',
        },
        {
          Condition: 'cCusType',
          Keyword: 1,
        },
      ],
      loading: false,
      modalLoading: false,
      columns,
      selectedRowKeys: [],
      selectedRows: [],
      searchTipResultList: [],
    }
  },
  methods: {
    // 休眠
    dormancy(id) {
      // this.loading = true
      console.log(id)
      this.$confirm('确定要休眠吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$http.post('/CustomerManagement/CustomerInfo/DormancyCustomerInfoSet', id).then((res) => {
          this.loading = false
          if (res.Success) {
            this.$message.success('操作成功')
            this.getDataList()
          } else {
            this.$message.error(res.Msg)
          }
        })
      })
    },
    inputKeyDown(e) {
      if (e.keyCode === 13) {
        if (!this.queryParam.cCusName) return this.$message.error('请输入查询条件')

        this.getDataList()
      }
    },
    changeSelect(e) {
      const idx = this.User.findIndex((item) => item.Id == e)

      if (idx !== -1) {
        this.entity.SalesmanName = this.User[idx].RealName
      }
    },
    validatePass(rule, value, callback) {
      if (this.Type) callback()
      else callback(new Error('请选择'))
    },
    saveAllocation() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return
        }
        this.modalLoading = true
        this.$http.post('/CustomerManagement/Cust_CustomerAllocation/SaveDormancy', this.entity).then((res) => {
          this.modalLoading = false
          if (res.Success) {
            this.$message.success('操作成功')
            this.getDataList()
            this.show = false
          } else {
            this.$message.error(res.Msg)
          }
        })
      })
    },
    follow(record) {
      this.entity = {}
      this.entity.CustomerId = record.Id
      this.show = true
    },
    Department(e) {
      this.$set(this.entity, 'SalesmanId', '')
      this.UserList(e)
    },
    UserList(e) {
      this.$http.post('/Base_Manage/Base_User/GetDataListAsyncByDeptId?DeptId=' + e).then((resJson) => {
        if (resJson.Success) {
          this.User = resJson.Data
        }
      })
    },
    PllAoo() {
      this.$refs.PllAOO.openForm()
    },
    handleAdd() {
      this.$refs.Detail.openForm(null, '添加')
    },
    handleRevise(id) {
      this.$refs.Detail.openForm(id, '编辑')
    },
    // 省市区的模糊查询
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    Cancel(row) {
      var thisObj = this
      this.$confirm('确定取消分配吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        return new Promise((resolve, reject) => {
          thisObj.$http
            .post(
              `/CustomerManagement/Cust_CustomerAllocation/DeleteDataForDissolution?CustomerId=${row.cCusCode}&&IsFormal= true`
            )
            .then((resJson) => {
              resolve()

              if (resJson.Success) {
                thisObj.$message.success('操作成功!')

                thisObj.getDataList()
              } else {
                thisObj.$message.error(resJson.Msg)
              }
            })
        })
      })
    },
    Repossess() {
      this.queryParam = [
        {
          Condition: 'cCusName',
        },
        {
          Condition: 'cCusType',
          Keyword: 1,
        },
      ]
      this.DormancySetDate = moment(new Date())
    },
    CheckboxProps(record) {
      return {
        props: {
          disabled: record.AllocationStatus === 1,
        },
      }
    },

    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      this.getDataList()
    },
    Distribute(row) {
      this.IsFormal = true
      this.$refs.MyCustomer.openForm(row, '分配客户')
    },
    getDataList() {
      this.selectedRowKeys = []
      this.searchTipResultList = [] //清空搜索提示列表

      this.loading = true
      this.$http
        .post('/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreConditionForDormancy', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          DeptId: this.DeptId,
          Search: {
            DormancySetDate: this.DormancySetDate,
            Conditions: this.queryParam,
          },
          ...this.filters,
        })
        .then((resJson) => {
          this.loading = false
          this.data = resJson.Data
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    contactPerson(row) {
      this.$refs.List.openForm(row, '客户联系人')
    },

    handleEdit(id) {
      this.$refs.details.openForm(id, '客户详情')
    },
    handleDelete(ids) {
      var thisObj = this
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        return new Promise((resolve, reject) => {
          thisObj.$http.post('/CustomerManagement/Cust_CustomerInfoFormal/DeleteData', ids).then((resJson) => {
            resolve()

            if (resJson.Success) {
              thisObj.$message.success('操作成功!')

              thisObj.getDataList()
            } else {
              thisObj.$message.error(resJson.Msg)
            }
          })
        })
      })
    },
    timeFormat(val) {
      // 日期格式化函数
      return moment(val).format('YYYY-MM-DD HH:mm')
    },
    async toGetSearchTipList(e) {
      this.searchTipResultList = []
      this.queryParam[0].keyword = e
      if (!this.queryParam[0].keyword) {
        return
      }
      await this.$http
        .post('/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreConditionForDormancy', {
          PageIndex: 1,
          PageRows: 50,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          DeptId: this.DeptId,
          Search: {
            DormancySetDate: this.DormancySetDate,
            Conditions: this.queryParam,
          },
          ...this.filters,
        })
        .then((resJson) => {
          if (resJson.Success && this.queryParam[0].keyword) {
            this.searchTipResultList = resJson.Data.map((e) => e.cCusName).slice(0, 10)
          } else {
            this.searchTipResultList = []
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    selectSearchTipFun(text) {
      this.queryParam[0].keyword = text
      this.searchTipResultList = []
      this.getDataList()
    },

    keywordBlurFun() {
      this.searchTipResultList = []
    },
  },
}
</script>
